/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.xxl.adapter.dao;

import cn.hutool.core.collection.CollectionUtil;
import com.xxl.adapter.core.XxlConvert;
import com.xxl.adapter.entity.JobRegistry;
import com.xxl.adapter.repository.JobRegistryRepository;
import com.xxl.job.admin.core.model.XxlJobRegistry;
import com.xxl.job.admin.dao.XxlJobRegistryDao;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * XxlJobRegistryDaoImpl
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
@Component
public class JobRegistryDaoImpl implements XxlJobRegistryDao, XxlConvert {

  @Autowired private JobRegistryRepository repository;

  @Override
  public List<Integer> findDead(int timeout, Date nowTime) {
    return repository
        .findAll(
            (root, query, cb) -> {
              Date date = new Date(nowTime.getTime() - timeout * _1_SECOND);

              return cb.lessThan(root.get("updateTime"), date);
            })
        .stream()
        .map(JobRegistry::getId)
        .collect(Collectors.toList());
  }

  @Override
  public int removeDead(List<Integer> ids) {
    repository.deleteAllById(ids);
    return 1;
  }

  @Override
  public List<XxlJobRegistry> findAll(int timeout, Date nowTime) {
    return this.convert(
        XxlJobRegistry.class,
        repository.findAll(
            (root, query, cb) -> {
              Date date = new Date(nowTime.getTime() - timeout * _1_SECOND);

              return cb.greaterThan(root.get("updateTime"), date);
            }));
  }

  @Override
  public int registryUpdate(
      String registryGroup, String registryKey, String registryValue, Date updateTime) {
    List<JobRegistry> list =
        repository.findAll(
            (root, query, cb) ->
                cb.and(
                    cb.equal(root.get("registryGroup"), registryGroup),
                    cb.equal(root.get("registryKey"), registryKey),
                    cb.equal(root.get("registryValue"), registryValue)));

    if (CollectionUtil.isNotEmpty(list)) {
      list.forEach(i -> i.setUpdateTime(updateTime));
      repository.saveAll(list);

      return 1;
    }

    return 0;
  }

  @Override
  public int registrySave(
      String registryGroup, String registryKey, String registryValue, Date updateTime) {
    JobRegistry jobRegistry = new JobRegistry();
    jobRegistry.setRegistryGroup(registryGroup);
    jobRegistry.setRegistryKey(registryKey);
    jobRegistry.setRegistryValue(registryValue);
    jobRegistry.setUpdateTime(updateTime);
    jobRegistry = repository.save(jobRegistry);

    return jobRegistry.getId();
  }

  @Override
  public int registryDelete(String registryGroup, String registryKey, String registryValue) {
    List<JobRegistry> list =
        repository.findAll(
            (root, query, cb) ->
                cb.and(
                    cb.equal(root.get("registryGroup"), registryGroup),
                    cb.equal(root.get("registryKey"), registryKey),
                    cb.equal(root.get("registryValue"), registryValue)));
    if (CollectionUtil.isNotEmpty(list)) {
      repository.deleteAll(list);
    }

    return 1;
  }

  @Override
  public Logger getLogger() {
    return log;
  }
}
